package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yangeit
 * @date 2023年11月18日 11:09
 * @Description
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;


    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;




    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWithFlavor(DishDTO dto) {
//        1.保存基本信息到dish表
//        1.1 讲dishdto-->dish
         Dish dish = new Dish();
         BeanUtils.copyProperties(dto,dish);
         dishMapper.insert(dish); //只有insert陈工了，才有dishid--返回主键
         Long dishId = dish.getId();
//        2. 保存口味信息到dish_flavor表
         List<DishFlavor> flavors = dto.getFlavors();

        if (flavors!=null &&flavors.size()>0){
//            for (DishFlavor flavor : flavors) {
//                flavor.setDishId(dishId);
//            }
            flavors.stream().forEach(flavor->{
                flavor.setDishId(dishId);
            });

        //        批量插入
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public PageResult page(DishPageQueryDTO dto) {
//        1.使用分页插件开启分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
//        2. 使用mapper动态查询
         Page<DishVO> page = dishMapper.pageQuery(dto);

         PageResult pageResult = new PageResult(page.getTotal(), page.getResult());

        return pageResult;
    }

    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
//        注意事项:
//        1. 新增菜品-->dish表  dish_flavor表--->开事务
//        2. 能够根据ids的个数,执行批量删除或者单个删除--->foreach标签
//        3. 正在热卖(起售)的菜品 不能删除
//        4. 凡是被套餐关联的菜品,不能删除
//        5. 如果要某个菜品,需要连同口味一起删除

//        判断当前ids传过来的菜品ids.中是否有才是起售...

        for (Long id : ids) {
          Dish dish=  dishMapper.getById(id);

          if (dish.getStatus()==1){
//              抛异常
              throw new DeletionNotAllowedException("菜品热卖中...不能删除");
          }
        }


//        判断当前菜品有没有被套餐关联 如果有 不能删除
         List<Long> setmeal_ids=   setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmeal_ids!=null &&setmeal_ids.size()>0){
            throw new DeletionNotAllowedException("选中菜品被套餐关联...不能删除");
        }

//        删除菜品表

        dishMapper.deleteByIds(ids);

//        删除才菜品对应的口味信息
        dishFlavorMapper.deleteByDishIds(ids);


    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
//         DishVO dishVO = new DishVO();
////         1. 先查询dish表,
//
//         Dish dish = dishMapper.getById(id);
//         BeanUtils.copyProperties(dish,dishVO);
//
//
////        2. 再根据id查询dish_flavor表
//       List<DishFlavor> dishFlavors=dishFlavorMapper.getFlavorsByDishId(id);
//
//
//
////        3. 分装到dishvo
//        dishVO.setFlavors(dishFlavors);

//        执行1条sql语句 返回DishVO  基本数据+集合数据

        DishVO dishVO =dishFlavorMapper.getByIdWithFlavor(id);
        return dishVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWithFlavor(DishDTO dto) {

         Dish dish = new Dish();
//        思路: 1. 修改基本表
        BeanUtils.copyProperties(dto,dish);

        dishMapper.update(dish);


//        2. 删除口味表
         ArrayList<Long> ids = new ArrayList<>();
        ids.add(dto.getId());
        dishFlavorMapper.deleteByDishIds(ids);


//        3. 重新添加对应的口味数据

        List<DishFlavor> flavors = dto.getFlavors();

        if (flavors!=null &&flavors.size()>0){

            flavors.stream().forEach(flavor->{
                flavor.setDishId(dto.getId());
            });

            //        批量插入
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getFlavorsByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public void updateStatus(Integer status, Integer id) {
         if (status==1){
             dishMapper.updateStatus0(status,id);
         }
         if (status==0){
             dishMapper.updateStatus1(status,id);
         }
    }

    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能够删除---是否存在起售中的菜品？？
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //判断当前菜品是否能够删除---是否被套餐关联了？？
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品表中的菜品数据
        for (Long id : ids) {
            dishMapper.deleteById(id);
            //删除菜品关联的口味数据
            dishFlavorMapper.deleteByDishId(id);
        }
    }
}
